package com.v2future.sjt.collegecheckingattendance;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.v2future.sjt.collegecheckingattendance.home.HomeActivity;
import com.v2future.sjt.collegecheckingattendance.home.bean.LoginResultBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.MD5;
import com.v2future.sjt.collegecheckingattendance.utils.PreferencesUtil;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;

/**
 * Created by minnie on 16/1/12.
 */
public class LoginActivity extends MainActivity {

    Button loginBtn;
    LinearLayout studentTabLayout, teacherTabLayout;
    EditText userNameEt, pwdEt;
    TextView userNameTv;
    TextView titleTv;
    TextView baseLineTv;

    public final int STUDENT = 2;
    public final int TEACHER = 1;
    private int user = STUDENT;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void init() {

    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_login);
        titleTv = (TextView) findViewById(R.id.textView);
        baseLineTv = (TextView) findViewById(R.id.tv_baseline);
        studentTabLayout = (LinearLayout) findViewById(R.id.layout_native_student);
        studentTabLayout.setOnClickListener(mClickListener);
        teacherTabLayout = (LinearLayout) findViewById(R.id.layout_native_teacher);
        teacherTabLayout.setOnClickListener(mClickListener);
        userNameEt = (EditText) findViewById(R.id.et_username);
        pwdEt = (EditText) findViewById(R.id.et_password);
        pwdEt.setOnKeyListener(onInputKeyListener);
        userNameTv = (TextView) findViewById(R.id.tv_username);
        loginBtn = (Button) findViewById(R.id.btn_login);
        loginBtn.setOnClickListener(mClickListener);
    }

    @Override
    public void initAfter() {
        //是否有已保存的登录信息
//        String username = PreferencesUtil.getSharedStringData(LoginActivity.this, Constants.PREFERENCE_USERNAME);
//        String pwd = PreferencesUtil.getSharedStringData(LoginActivity.this, Constants.PREFERENCE_PWD);
//        String userType = PreferencesUtil.getSharedStringData(LoginActivity.this, Constants.PREFERENCE_USER_TYPE);
//        if (!TextUtils.isEmpty(username) &&
//                !TextUtils.isEmpty(pwd)) {
//            clickLogin(username, pwd, userType);
//        }
        listenerSoftInput();
    }

    @Override
    public void inputActionEvent() {
        super.inputActionEvent();
        try {
            clickLogin(userNameEt.getText().toString(), MD5.getMD5(pwdEt.getText().toString()), user+"");
        }catch (Exception e) {
            e.printStackTrace();
            tip("登录错误");
        }
    }

    View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_login:
                    try {
                        clickLogin(userNameEt.getText().toString(), MD5.getMD5(pwdEt.getText().toString()), user+"");
                    }catch (Exception e) {
                        e.printStackTrace();
                        tip("登录错误");
                    }
                    break;
                case R.id.layout_native_student:
                    clickNativeTab(v);
                    break;
                case R.id.layout_native_teacher:
                    clickNativeTab(v);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 登录按钮点击
     */
    public void clickLogin(final String username, final String pwd, final String userType) {
        if (TextUtils.isEmpty(userNameEt.getText().toString()) ||
                TextUtils.isEmpty(pwdEt.getText().toString())) {
            tip(R.string.username_pwd_not_null);
            return;
        }
        //请求地址
        BaseRequestParams params = new BaseRequestParams(formatUrl(Constants.LOGIN));
        //请求参数
        params.addQueryStringParameter("passWord", pwd);
        params.addQueryStringParameter("userCode", username);
        params.addQueryStringParameter("sourceTypeId", userType);
        showLoadingDialog();
        NetUtils.doGetRequest(this, params, new NetTaskListener<LoginResultBean>() {

            @Override
            public void onSuccess(LoginResultBean result) {
                //保存当前用户到本地内存
                getBaseApplication().insertCathe(Constants.CACHE_KEY_USER_INFO, result);
                //保存当前用户到本地磁盘，用来自动登录
                PreferencesUtil.setSharedStringData(LoginActivity.this, Constants.PREFERENCE_USERNAME, username);
                PreferencesUtil.setSharedStringData(LoginActivity.this, Constants.PREFERENCE_PWD, pwd);
                PreferencesUtil.setSharedStringData(LoginActivity.this, Constants.PREFERENCE_USER_TYPE, userType);
                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                finish();
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(LoginResultBean result) {
                tip(result.getFailReason());
            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            @Override
            public void onSuccessCache(LoginResultBean result) {
                //未使用缓存
            }
        });
    }

    /**
     * 监听软键盘
     */
    private void listenerSoftInput() {
        final View activityRootView = findViewById(R.id.layout_root);
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new  ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int heightDiff = activityRootView.getRootView()
                        .getHeight() - activityRootView.getHeight();
                        if (heightDiff > 100) { // 如果高度差超过100像素，就很有可能是有软键盘...
                            baseLineTv.setVisibility(View.GONE);
                            titleTv.setVisibility(View.GONE);
                        }
                        else {
                            baseLineTv.setVisibility(View.VISIBLE);
                            titleTv.setVisibility(View.VISIBLE);
                        }
            }
        });
    }

    public void clickNativeTab(View v) {
        if (R.id.layout_native_student == v.getId()) {
            if (TEACHER == user) {
                user = STUDENT;
                teacherTabLayout.setBackgroundResource(R.color.main_fore);
                studentTabLayout.setBackgroundResource(R.drawable.bg_native_selected);
                userNameTv.setText(R.string.student_code);
            }
        } else if (R.id.layout_native_teacher == v.getId()) {
            if (STUDENT == user) {
                user = TEACHER;
                studentTabLayout.setBackgroundResource(R.color.main_fore);
                teacherTabLayout.setBackgroundResource(R.drawable.bg_native_selected);
                userNameTv.setText(R.string.teache_code);
            }
        }
    }
}
